import React, { useState, useEffect } from "react";
import { Radio, Input, Select, Button } from "antd";
import useModelList from "@/hooks/useModelList";
import showToast from "@/utils/message";
import { invokeAsyncAPi } from "@/xz-fn.js";
import ModalLocalDeploy from "@/components/ModalLocalDeploy";
import System from "@/models/system";
import Llm from "@/media/model/llm.png";
import Oll from "@/media/model/Oll.png";
import DeepSeek from "@/media/model/deepseek.png";
const App = ({ handleCancel }) => {
  const modeData = useModelList();
  const APINAME = "http://localhost:11434";
  const [install, setInstall] = useState();
  const [modelType, setModelType] = useState(1);
  const [modelList, setModelList] = useState([]);
  const [openLocal, setOpenLocal] = useState(false);
  const [apiName, setApiName] = useState(APINAME);
  const [modelName, setModelName] = useState();
  const changeModelType = (value) => {
    setModelType(value);
    setModelList([]);
    setModelName("");
    if (value == 2) {//在线模型，判断是否登录
      console.log("请登录");
      const modelList =
        modeData.map((item) => ({
          value: item.id,
          label: item.title,
        })) || [];
      setModelList(modelList);
      setModelName(modelList[0]?.value);
    } else if (value == 1) {
      getModelList();
    }
  };

  const handleInputChange = (e) => {
    console.log("Input value changed:", e.target.value);
    setApiName(e.target.value); // 更新状态变量
  };

  const handleSelectChange = (value) => {
    console.log(`Selected model: ${value}`);
    setModelName(value); // 更新状态变量
  };

  // 重置按钮的处理函数
  const handleReset = () => {
    setApiName(APINAME);
    setModelName(modelList[0]?.value);
    setModelType(1);
  };

  const handleSave = async () => {
    const data = {
      LLMProvider: "ollama",
      OllamaLLMAuthToken: "",
      OllamaLLMBasePath: "http://127.0.0.1:11434",
      OllamaLLMKeepAliveSeconds: "300",
      OllamaLLMModelPref: modelName,
      OllamaLLMPerformanceMode: "base",
      OllamaLLMTokenLimit: "4096",
    };
    const { error } = await System.updateSystem(data);
    if (error) {
      showToast("error", "模型设置失败");
    } else {
      showToast("success", "模型设置成功");
      localStorage.setItem("providerType", modelType);
    }
    handleCancel();
  };

  const prefixStyle = {
    visibility: apiName ? "visible" : "hidden",
    overflow: "hidden",
    padding: apiName ? "0 11px" : 0, // 恢复 Ant Design 默认的 padding
  };
  useEffect(() => {
    try {
      const ollamaStatus = invokeAsyncAPi("xz_check_ollama_install")
        .then((res) => {
          console.log(res);
          setInstall(res);
          if (res) {
            getModelList();
          }
        })
        .catch((err) => {
          console.error(err);
          return false; // 如果发生错误，返回false表示未安装
        });
      console.log("判断是否安装过ollama", ollamaStatus);
    } catch (error) {
      console.error("Error initializing data:", error);
    }
  }, []); // 空依赖数组，只在组件挂载时执行一次

  const getModelList = async () => {
    try {
      const list = await invokeAsyncAPi("xz_get_ai_model_list");
      const modelList =
        list.map((item) => ({
          value: item.name,
          label: item.name,
        })) || [];
      setModelList(modelList);
      setModelName(modelList[0]?.value);
      console.log("获取模型列表成功", modelList);
      // 处理模型列表数据
    } catch (error) {
      console.error(error);
    }
  };
  return (
    <>
      <div className="content-top h-[420px]">
        <div className="text-[14px] font-semibold text-theme-text-default">
          LLM提供者
        </div>
        <Radio.Group
          className="flex items-center justify-between w-[300px] my-[14px] text-[14px] text-theme-text-default"
          name="radiogroup"
          defaultValue={1}
          onChange={(e) => {
            changeModelType(e.target.value);
          }}
          options={[
            { value: 1, label: "本地模型" },
            { value: 2, label: "在线模型" },
          ]}
        />

        {modelType == 2 ? (
          <div className="flex items-center text-[14px] text-theme-text-default">
            <img src={Llm} alt="Logo" className="h-[24px] w-[24px] mr-[6px]" />
            <span className="text-theme-text-default">系统默认</span>
          </div>
        ) : (
          <div className="flex flex-col text-[14px] text-theme-settings-sub">
            <div className="flex items-center text-[13px]">
              <img src={Oll} alt="Oll" className="h-[24px] w-[24px] mr-[6px]" />
              <span>Ollama&nbsp;&nbsp;</span>
              {!install && (
                <div>
                  <span>暂不可用，</span>
                  <span
                    className="text-theme-settings-selected cursor-pointer"
                    onClick={() => {
                      setOpenLocal(true);
                    }}
                  >
                    立即本地部署模型
                  </span>
                </div>
              )}
            </div>
            {!install && (
              <p className="text-[12px] leading-loose">
                包含海量模型：Deepseek、OpenAi、GPT-4、LangChain、PineconeDB、ChromaDB...
              </p>
            )}
          </div>
        )}

        {(install || modelType == 2) && (
          <>
            <div className="flex flex-col text-[14px] text-theme-text-default font-semibold my-[24px]">
              <p className="mb-[12px]">API域名</p>
              <Input
                placeholder="在此输入"
                suffix={
                  <span
                    style={prefixStyle}
                    onClick={() => {
                      setApiName(APINAME);
                    }}
                  >
                    重置
                  </span>
                }
                value={apiName}
                onChange={handleInputChange}
              />
            </div>

            <div className="flex flex-col text-[14px] text-theme-text-default font-semibold">
              <p className="mb-[12px]">聊天模型</p>
              <div className="flex items-center justify-between">
                <div className="flex items-center h-[36px] rounded-[8px] select-box relative flex-1">
                  <img
                    src={DeepSeek}
                    alt="DeepSeek"
                    className="absolute w-[28px] h-[28px] left-[10px]"
                  />
                  <Select
                    value={modelName}
                    onChange={handleSelectChange}
                    className="select-div w-full pl-[30px]"
                    options={modelList}
                  />
                </div>
                <div
                  className="text-[#165DFF] text-[14px] ml-[14px] cursor-pointer"
                  onClick={() => {
                    setOpenLocal(true);
                  }}
                >
                  下载更多模型
                </div>
              </div>
            </div>
          </>
        )}
      </div>
      <div className="content-bottom flex items-center justify-end">
        <Button color="default" variant="link" onClick={handleCancel}>
          取消
        </Button>
        <Button type="link" onClick={handleReset}>
          重置
        </Button>
        <Button color="primary" variant="link" onClick={handleSave}>
          保存
        </Button>
      </div>

      {openLocal && (
        <ModalLocalDeploy
          showLocalModal={openLocal}
          hideLocalDeploy={() => {
            setOpenLocal(false);
          }}
        />
      )}
    </>
  );
};
export default App;
